#define THIS_FILE "sniper.sqf"
#include <base\tmf_constants.h>
#include <base\tmf_macros.h>
WAITINIT(sniper);

if(!isServer) exitWith{};

private["_pos","_max_dist","_grp"];

_grp = _this select 0;
if (typename _grp == typename objNull) then {
	_grp = group _grp;
};
_pos = _this select 1;
_max_dist = _this select 2;
_debug = if ((count _this) > 3) then {_this select 3} else {false};

_units = units _grp;

_building_pos_sniper = [_pos,_max_dist,"SNIPER"] call XfMissionBuildingAreaPosASL;

// We check if there are buildings elligible for snipers.
if (count _building_pos_sniper > 0) then {
	if (_debug) then { diag_log Format["TaskSniper [%1]: Snipers %2, Positions %3",_grp, count _units, count _building_pos_sniper]; };
	_building_pos_sniper = _building_pos_sniper call XfRandomArray;

	_quantity = (count _units) min (count _building_pos_sniper);
	for [{_i=0}, {_i < _quantity}, {_i=_i+1}] do
	{
		_unit = _units select _i;
		doStop _unit;
		// Will prevent the unit from moving and falling from roofs.
		_pos = _building_pos_sniper select _i;
		_unit setPosASL _pos;
		_unit setUnitPos "Middle";
		[_unit] call XfMissionStuckUnit;
		if (_debug) then { 
			_marker = createMarkerLocal [Format["SniperMarker%1",_i], _pos];
			_marker setMarkerShapeLocal "ICON";
			_marker setMarkerTypeLocal "mil_triangle";
			_marker setMarkerColorLocal "ColorPink";
			_marker setMarkerTextLocal Format["S%1",_i];
		};	
	};
	if (_quantity < (count _units)) then {
		for [{_i=_quantity}, {_i < (count _units)}, {_i=_i+1}] do
		{
			_unit = units _newgroup select _i;
			doStop _unit;
			// Do something with Remainder units
			
			// _pos = _building_pos_sniper select _i;
			// _unit setPosASL _pos;
			// _unit setUnitPos "Middle";
			// [_unit] call XfMissionStuckUnit;
			if (_debug) then { 
				_marker = createMarkerLocal [Format["SniperMarker%1",_i], _pos];
				_marker setMarkerShapeLocal "ICON";
				_marker setMarkerTypeLocal "mil_triangle";
				_marker setMarkerColorLocal "ColorOrange";
				_marker setMarkerTextLocal Format["S%1",_i];
			};	
		};
	};
	if (_debug) then { diag_log Format["TaskSniper [%1]: Placed %2 units",_grp, _quantity]; };
} else {
	diag_log Format["TaskSniper [%1]: Creating %2 WPs (%3)",_grp, _wp_count, _min_dist];
};